package com.icloud.framework.query;

import java.util.*;

public class TreeUtils {

    public static <T extends TreeNode>  List<T> createTree(List<T> nodes) {
        List<T> trees = new ArrayList<T>();
        if (null != nodes && !nodes.isEmpty()) {

            // 组装Map数据
            Map<String, T> dataMap = new HashMap<String, T>();
            for (T node : nodes) {
                dataMap.put(node.findKey(), node);
            }
            // 组装树形结构
            Set<Map.Entry<String, T>> entrySet = dataMap.entrySet();

            for (Map.Entry<String, T> entry : entrySet) {
                T menu = entry.getValue();
                if (menu.findParentId()==null ||menu.findParentId()=="") {
                    //一级菜单
                    trees.add(menu);
                } else {
                    dataMap.get(menu.findParentId()).findChildren().add(menu);
                }
            }

            // 对树形结构进行二叉树排序
            for(T node:trees){
                node.sortChildren();
            }
        }
        return trees;
    }
}
